
#include <Irrlicht.h>
#include "ASpriteInstance.h"
#include "ASprite.h"
#include "CGlobals.h"

extern CGlobals* g;

ASpriteInstance::ASpriteInstance()
{
	x = 0;
	y = 0;
	m_nCurrentSprite = NULL;

	Stop();

	m_nLastUpdateTime = g->device->getTimer()->getRealTime();

	m_scaleX = 1.0f;
	m_scaleY = 1.0f;
}

ASpriteInstance::~ASpriteInstance()
{

}

void ASpriteInstance::Stop()
{
	m_nCurrentAnim = -1;
	m_nCurrentAFrame = 0;
	m_nCurrentFTime = 0;
	m_nCurrentAnimTime = 0;
	//m_nLoop = 0xFFFFFF;
	m_nNextAnim = -1;
}

void ASpriteInstance::SetAnim(int anim, int loop)
{
	Stop();

	m_nCurrentAnim = anim;
	m_nLoop = loop;
}

void ASpriteInstance::SetPosition(int x, int y)
{
	this->x = x;
	this->y = y;
}

void ASpriteInstance::SetASprite(ASprite* sprite)
{
	m_nCurrentSprite = sprite;
}

void ASpriteInstance::StartAnim(ASprite* sprite, int anim, int x, int y, int loop)
{
	Stop();

	m_nCurrentSprite = sprite;
	m_nCurrentAnim = anim;
	this->x = x;
	this->y = y;
	m_nLoop = loop;
}

void ASpriteInstance::SetTransitionAnim(int anim, int nextAnim)
{
	SetAnim(anim);
	m_nNextAnim = nextAnim;
}

void ASpriteInstance::Update()
{
	if(m_nCurrentSprite == NULL || m_nCurrentAnim < 0)
		return;

	u32 currentTime = g->device->getTimer()->getRealTime();
	if(currentTime - m_nLastUpdateTime < 1000/16)
		return;
	
	m_nLastUpdateTime = g->device->getTimer()->getRealTime();
	int time = m_nCurrentSprite->GetAFrameTime(m_nCurrentAnim, m_nCurrentAFrame);

	if(time == 0)
	{
		return;
	}

	m_nCurrentFTime++;
	m_nCurrentAnimTime++;

	if(m_nCurrentFTime < time)
    {
        return;
    }

	m_nCurrentFTime = 0;
    m_nCurrentAFrame++;
    		
    if(m_nCurrentAFrame >= m_nCurrentSprite->GetAFrames(m_nCurrentAnim))
    {		
		if(m_nNextAnim >= 0)
		{
			SetAnim(m_nNextAnim);
		}
		else
		{
			m_nLoop--;
			if(m_nLoop < 0)
			{
				Stop();
			}
			else
			{
				m_nCurrentAFrame	= 0;
				m_nCurrentAnimTime	= 0;
				m_nNextAnim = -1;
			}
		}
	}
}

bool ASpriteInstance::IsAnimEnded()
{
	return (m_nLoop < 0) && m_nCurrentAFrame == 0 && m_nCurrentFTime == 0; 
}

void ASpriteInstance::Draw()
{
	if(m_nCurrentSprite == NULL || m_nCurrentAnim < 0)
		return;
		
	m_nCurrentSprite->PaintAFrame(m_nCurrentAnim, m_nCurrentAFrame, x, y, 0, 0, 0);	
}

void ASpriteInstance::Draw3D(const irr::core::vector3df& pos)
{
	if(m_nCurrentSprite == NULL || m_nCurrentAnim < 0)
		return;
		
	m_nCurrentSprite->PaintAFrame3D(m_nCurrentAnim, m_nCurrentAFrame, pos, 0, 0, 0, SPRITE_SCALE_3D * m_scaleX, SPRITE_SCALE_3D * m_scaleY);
}